<template>
  <span v-html="rendered"></span>
</template>

<script setup>
import { computed } from 'vue'
import katex from 'katex'

const props = defineProps({
  text: String
})

function wrapChineseInMath(str) {
  // 只处理$...$和$$...$$中的中文
  return str.replace(/(\${1,2})([^$]+?)\1/g, (match, dollar, content) => {
    // 把content中的中文替换为\text{...}
    const replaced = content.replace(/[\u4e00-\u9fa5]+/g, (s) => `\\text{${s}}`)
    return `${dollar}${replaced}${dollar}`
  })
}

const rendered = computed(() => {
  try {
    const safeText = wrapChineseInMath(props.text || '')
    return katex.renderToString(safeText, { throwOnError: false, displayMode: false })
  } catch (e) {
    return props.text
  }
})
</script> 